package cn.bd13.swagger.controller;

import cn.bd13.swagger.entity.ReturnResult;
import cn.bd13.swagger.entity.User;
import cn.bd13.swagger.service.Service;
import cn.bd13.swagger.utils.RedisUtil;
import cn.bd13.swagger.utils.ReturnUtils;
import cn.bd13.swagger.utils.TokenUtils;
import com.alibaba.fastjson.JSON;
import cz.mallat.uasparser.UserAgentInfo;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api("这是有token和redis处理的用户逻辑类")
@RequestMapping("/xin")
public class TokenController {


    @Autowired
    private Service service;

    @Autowired
    private RedisUtil redisUtil;

    @ApiOperation(value = "token方式登录",notes = "。。。")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name",required = true,paramType = "path"),
            @ApiImplicitParam(name = "password",required = true,paramType = "path")
    })
    @ApiResponses({
            @ApiResponse(code = 403,message = "密码错误"),
            @ApiResponse(code = 406,message = "昵称错误"),
            @ApiResponse(code = 502,message = "数据库操作错误")
    })
    @RequestMapping(value = "/loginByPwd/{name}/{password}",method = RequestMethod.POST)
    public ReturnResult loginByPwd(@PathVariable String name, @PathVariable String password,HttpServletRequest request){
        //检查登录信息是否正确
        try {
            User user = service.getUserName(name);

            if (user!=null){
                if (password.equals(user.getPassword())){
                    //检查正确
                    //解析这个请求的设备信息
                    String userAgent= request.getHeader("User-Agent");
                    UserAgentInfo userAgentInfo=TokenUtils.uaSparser.parse(userAgent);
                    String dType=userAgentInfo.getDeviceType();
                    //生成token
                    //String token= TokenUtils.createToken(user.getName());
                    String token=TokenUtils.createToken(user.getName(),dType);
                    //将token存入redis（先判断redis中有没有）
                    saveToken(token,user);
                    //这是将用户信息放在data中，token信息放在msg中
                      return ReturnUtils.returnSuccessWithData(user,token);
//                    Map<String,Object> dataMap=new HashMap<>();
//                    dataMap.put("user",user);
//                    dataMap.put("token",token);
//                    return ReturnUtils.returnSuccessWithData(dataMap);
                }else{
                    //密码错误
                    return ReturnUtils.returnFailed(403);
                }
            }else{
                //昵称错误
                return ReturnUtils.returnFailed(406);
            }
        } catch (Exception e) {
            //查询中出现异常
            e.printStackTrace();
            return ReturnUtils.returnFailed(502);
        }
    }


    @RequestMapping("/getAllUserInfo")
    public ReturnResult getAllUserInfo(HttpServletRequest request){

        String token = request.getHeader("token");
        if (token==null||token.equals("")){
            return ReturnUtils.returnFailed(403,"没有登录,请先登录");
        }else{
            String userJson=redisUtil.get(token);
            if (userJson==null||userJson.equals("")){
                return ReturnUtils.returnFailed(403,"没有权限,请登录");
            }else{
                try {
                    User user = (User) JSON.parseObject(userJson,User.class);
                    List<User> users=service.getAllUser();
                    return ReturnUtils.returnSuccessWithData(users,"你是："+user.getName());
                } catch (Exception e) {
                    e.printStackTrace();
                    return ReturnUtils.returnFailed(500);
                }
            }

        }


    }



    private void saveToken(String token,User user)throws Exception{

        String tokenKey="user-"+user.getId();
        String tokenValue=null;
        if ((tokenValue=redisUtil.get(tokenKey))!=null){
            //用户已经登录过，而且没有过期
            redisUtil.delete(tokenKey);
        }
        //缓存用户
        redisUtil.set(tokenKey,token,100);
        //缓存用户信息
        redisUtil.set(token, JSON.toJSONString(user),1800);
    }



}
